package com.jielin.handling.service.record.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jielin.handling.entity.record.RecordCommonalityModel;
import com.jielin.handling.mapper.record.RecordAnswerMapper;
import com.jielin.handling.mapper.record.RecordCommonalityModelMapper;
import com.jielin.handling.mapper.record.RecordQuestionMapper;
import com.jielin.handling.service.record.RecordCommonalityModelService;
import com.jielin.handling.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class RecordCommonalityModelServiceimpl implements RecordCommonalityModelService {
	@Autowired
	private RecordCommonalityModelMapper recordCommonalityModelMapper;
	@Autowired
	private RecordQuestionMapper recordQuestionMapper;
	@Autowired
	private RecordAnswerMapper recordAnswerMapper;

	@Override
	public List<RecordCommonalityModel> findCommonalityByModelId(String modeltypeid, String policeId) {
		if (StringUtil.isEmpty(modeltypeid)) {
			return null;
		}
		return recordCommonalityModelMapper.findCommonalityByModelId(modeltypeid, policeId);
	}

	@Override
	public List<RecordCommonalityModel> findMyModelById(String policeId) {
		if (StringUtil.isEmpty(policeId)) {
			return null;
		}
		return recordCommonalityModelMapper.findMyModelById(policeId);
	}

	@Override
	public int addMyModel(RecordCommonalityModel rcm) {
		if (rcm == null) {
			return -1;
		}
		return recordCommonalityModelMapper.addMyModel(rcm);
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int deleteMyModel(RecordCommonalityModel rcm) {
		int i = -1;
		String trueUserId = recordCommonalityModelMapper.findModelPoliceIdByModelId(rcm.getId());
		if (!StringUtil.isEmpty(trueUserId)) {
			if (!trueUserId.equals(rcm.getUserid())) {
				return -2;
			}
		}
		try {
			List<String> questions = recordQuestionMapper.findQuestionIdByModelId(rcm.getId());
			if (questions.size() > 0) {
				recordAnswerMapper.delByQuestionId(questions);// 删除答案
				recordQuestionMapper.delByModelId(rcm.getId());// 删除问题
			}
			recordCommonalityModelMapper.deleteById(rcm.getId());// 删除模板
			i = 1;
		} catch (Exception e) {
			log.info("RecordCommonalityModelService 事务回滚:{}", e);
			// 抛出异常让其回滚
			throw new RuntimeException("事务回滚");
		}
		return i;
	}

}
